package com.crazyteam.datasource.util;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.function.Supplier;

/**
 * @author guoyang
 * @Date 2018-01-09
 */
public class TransactionUtil {

    public static boolean doTransaction(PlatformTransactionManager transactionManager,
                                        Supplier<Boolean> supplier,
                                        TransactionDefinition transactionDefinition){
        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        try {
            if (supplier.get()){
                transactionManager.commit(status);
                return true;
            }else {
                transactionManager.rollback(status);
                return false;
            }
        }catch (Exception e){
            transactionManager.rollback(status);
            throw e;
        }
    }

    public static boolean doTransaction(PlatformTransactionManager transactionManager, Supplier<Boolean> supplier){
        return doTransaction(transactionManager, supplier, new DefaultTransactionDefinition());
    }
}
